//
//  LSFollowReadView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/9/6.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSFollowReadView.h"
#import "BKAudioPlayer.h"
#import "KZShadowButton.h"
#import "TYAttributedLabel.h"
#import "KZWaveRecordingView.h"
#import "KZAudioPlayOrRecordView.h"
#import "KYTestEngine.h"
#import "LSGetZSDManager.h"
#import "LSSaveZSDManager.h"
#import "DicMainView.h"
#import "WJTimeCircle.h"

//static NSInteger tipHeight = 200;
//static NSInteger bottomY = 200;

@interface LSFollowReadView ()<BKAudioPlayerDelegate,LSTYAttributedLabelDelegate,DicMainViewDelegate> {
    NSInteger tipHeight;
    NSInteger bottomY;
}

@property (nonatomic,strong) BKAudioPlayer *player;
/*标题栏*/
@property (nonatomic,strong) UIView *titleBarView;
/*定时器*/
@property (nonatomic,strong) NSTimer *timer;
/*时间*/
@property (nonatomic,assign) CGFloat second;
/*指示灯*/
@property (nonatomic,strong) UIView *indicatorView;
/*句子内容*/
@property (nonatomic,strong) LSTYAttributedLabel *contentLabel;
/*知识点分析Label*/
@property (nonatomic,strong) LSTYAttributedLabel *zsdLabel;

/**发音按钮*/
@property (nonatomic,strong) UIButton *playBtn;
/*操作提示视图*/
@property (nonatomic,strong) UIView *tipsView;
/*提示文字*/
@property (nonatomic,strong) UILabel *tipLabel;
/*录音按钮*/
@property (nonatomic,strong) KZWaveRecordingView *recordView;
/*声波视图*/
@property (nonatomic,strong) KZAudioPlayOrRecordView *volumeView;
/*正在评判*/
@property (nonatomic,strong) UIImageView * evaluatingView;
/*结果*/
@property (nonatomic,strong) UILabel *resultLabel;
/*是否重新作答过*/
//@property (nonatomic,assign) BOOL isReAnswer;
/*句子文本*/
@property (nonatomic,strong) NSMutableAttributedString *attr;
/*重新跟读*/
@property (nonatomic,strong) UIButton *reReadBtn;
/*下一题*/
@property (nonatomic,strong) KZShadowButton *nextBtn;
/*我的录音*/
@property (nonatomic,strong) UIButton *myRecordBtn;
/*参考录音*/
@property (nonatomic,strong) UIButton *trueRecordBtn;
/*是否使用按钮播放*/
@property (nonatomic,assign) BOOL isPlayAction;
/*是否正在播放*/
@property (nonatomic,assign) BOOL isPlaying;
/*分析结果*/
@property (nonatomic,copy) NSString *testResult;
/*播放速度*/
@property (nonatomic,assign) CGFloat playRate;
/*最后一题按钮显示*/
@property (nonatomic,assign) BOOL isNoMore;

@property (nonatomic,strong) DicMainView *dictView;

/*阅读速度*/
@property (nonatomic,assign) CGFloat readRate;

@property (nonatomic,strong) NSMutableArray *mutlCodeArr;
@property (nonatomic,strong) NSMutableArray *mutlNameArr;

/*倒计时*/
@property (nonatomic,strong) WJTimeCircle *timeCircleView;

@end

@implementation LSFollowReadView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //self.backgroundColor = [UIColor redColor];
        self.player = [[BKAudioPlayer alloc] init];
        self.player.delegateM = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
        
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        //self.backgroundColor = [UIColor redColor];
        self.player = [[BKAudioPlayer alloc] init];
        self.player.delegateM = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
        
    }
    return self;
}

- (void)setModel:(LSModelQues *)model {
    _model = model;
    
    tipHeight = 200;
    bottomY = 200;
    
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;
        
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    [self createUI];
}

- (void)createUI {
    [self addSubview:self.titleBarView];
    [self.titleBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(35);
    }];
    
    [self addSubview:self.tipsView];
    [self.tipsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(tipHeight);
    }];
    
    if (![self.model.ChildList.firstObject.ChildAnswer isEqualToString:@""]) {
        self.attr = [[NSMutableAttributedString alloc] initWithAttributedString: [self.model.ChildList.firstObject.ChildAnswer  dr_HtmlStringWithFontSize:15.0f]];
    } else {
        self.attr =  [[NSMutableAttributedString alloc] initWithAttributedString:[self.model.QuesBody dr_HtmlStringWithFontSize:15.0f]];
    }
    self.contentLabel.attributedText = self.attr;
    [self.contentLabel sizeToFit];
    [self addSubview:self.contentLabel];


    if (self.answerState==2) {
        
        [self addSubview:self.trueRecordBtn];
        self.trueRecordBtn.x = kWidth-10-80;
        
        /*
        [self.tipsView addSubview:self.tipLabel];
        self.tipLabel.text = @"系统评判结果";
        self.tipLabel.y = 85;
        
        [self.tipsView addSubview:self.resultLabel];
        self.resultLabel.text = @"不合格";
        self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
        self.resultLabel.y = 10;*/
        
    } else {
        
//        [self addSubview:self.playBtn];
//        self.playBtn.y = self.contentLabel.y + self.contentLabel.height+10;
//
//        [self addSubview:self.volumeView];
//        self.volumeView.y = self.playBtn.y+50;
//
//        [self.tipsView addSubview:self.tipLabel];
//
//        self.tipLabel.text = @"请听标准句子发音...";
//        [UIView animateWithDuration:0.3 animations:^{
//            self.tipLabel.y = 0;
//        } completion:^(BOOL finished) {
//            NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
//            [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
//        }];
        [self startTimeCircle];
    }
    
}

//开始倒计时
- (void)startTimeCircle {
    self.pasueState = 1;
    self.second = self.model.ReadTime;
    
    [self.tipsView addSubview:self.timeCircleView];
    [self.tipsView addSubview:self.tipLabel];
    self.timeCircleView.totalSecond = self.second;
    
    self.tipLabel.y = bottomY + tipHeight;
    self.tipLabel.text = @"请浏览试题,倒计时结束后开始准备训练\n(点击可提前结束浏览时间)";
    self.tipLabel.height = 30;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.timeCircleView.y=5;
        self.tipLabel.y = self.timeCircleView.y+5+self.timeCircleView.height;
        
    } completion:^(BOOL finished) {
        
    }];
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeAnim) userInfo:nil repeats:YES];
     [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)timeAnim{
    self.second = self.second-0.01;
    //NSLog(@"===%f",self.second);
    if (self.second <= 0.00) {
        [self timeCircleEnd];
    } else {
        self.timeCircleView.second = self.second;
    }
}

- (void)timeCircleEnd {
    [self.timer invalidate];
    self.timer = nil;
    
    self.timeCircleView.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.timeCircleView.y = bottomY+tipHeight;
        self.tipLabel.y = bottomY+tipHeight;
        
    } completion:^(BOOL finished) {
        [self.timeCircleView removeFromSuperview];
        self.timeCircleView = nil;
    }];
    
    [self showSenPlay];
}

- (void)showSenPlay {
    if(self.isReAnswer) {
        self.pasueState = 2;
    } else {
        self.pasueState = 0;
    }
    
    
    [self addSubview:self.playBtn];
    self.playBtn.y = self.contentLabel.y + self.contentLabel.height+10;
    
    [self addSubview:self.volumeView];
    self.volumeView.y = self.playBtn.y+50;
    
    [self.tipsView addSubview:self.tipLabel];
    
    self.tipLabel.text = @"请听标准句子发音...";
    [UIView animateWithDuration:0.3 animations:^{
        self.tipLabel.y = 0;
    } completion:^(BOOL finished) {
        NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
        [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
    }];
    
}


#pragma mark - 懒加载

/*倒计时*/
- (WJTimeCircle *)timeCircleView {
    if (!_timeCircleView) {
        //_timeCircleView = [[WJTimeCircle alloc] initWithFrame:CGRectMake((kWidth-73)/2,_topY,73, 73)];
        _timeCircleView = [[WJTimeCircle alloc] initWithFrame:CGRectMake((kWidth-73)/2,bottomY+tipHeight,73, 73)];
        _timeCircleView.arcFinishColor = [UIColor colorWithHex:0xededed];
        _timeCircleView.arcUnfinishColor = [UIColor colorWithHex:0x50c6f9];
        _timeCircleView.arcBackColor = [UIColor clearColor];
        _timeCircleView.baseColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
        _timeCircleView.width = 3;
        _timeCircleView.isStartDisplay = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(timeCircleEnd)];
        [_timeCircleView addGestureRecognizer:tap];
        _timeCircleView.userInteractionEnabled = YES;
    }
    return _timeCircleView;
}

/*标题栏*/
- (UIView *)titleBarView {
    if (!_titleBarView) {
        _titleBarView = [[UIView alloc] init];
        UILabel *label = [[UILabel alloc] init];
        [_titleBarView addSubview:label];
        label.font = FONT(13);
        label.textColor = [UIColor colorWithHex:0x333333];
        NSString *text = [NSString stringWithFormat:@"第%ld题(共%ld题)",self.currentIndex+1,self.allCount];
        
        if (self.answerState==2) {
            text = @"句子跟读";
        }
        
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange range = [text rangeOfString:[NSString stringWithFormat:@"第%ld题",self.currentIndex+1]];
        
        if (self.answerState==2) {
            range = NSMakeRange(0, text.length);
        }
        
        [attr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x0693c8] range:range];
        label.attributedText = attr;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_titleBarView).offset(11);
            make.centerY.equalTo(_titleBarView);
            make.size.mas_offset(CGSizeMake(100, 13));
        }];
        
        UILabel *line = [[UILabel alloc] init];
        line.backgroundColor = [UIColor colorWithHex:0xededed];
        [_titleBarView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_titleBarView);
            make.bottom.equalTo(_titleBarView).offset(-0.5);
            make.height.mas_equalTo(0.5);
        }];
    }
    return _titleBarView;
}

- (UIView*)indicatorView {
    
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc] init];
        
        for (NSInteger i = 0; i<4; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            [_indicatorView addSubview:imageView];
            imageView.tag = 1003-i;
            imageView.alpha = 1;
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"LS-指示灯%ld",i+1]];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_indicatorView).offset(12+i*16);
                make.centerY.equalTo(_indicatorView);
                make.size.mas_equalTo(CGSizeMake(10, 10));
            }];
        }
    }
    
    return _indicatorView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-40)/2, 0,44, 44)];
        [_playBtn setBackgroundImage:[UIImage imageNamed:@"kz-发音图标"] forState:UIControlStateNormal];
        _playBtn.userInteractionEnabled = NO;
    }
    return _playBtn;
}

- (LSTYAttributedLabel *)contentLabel {
    if (!_contentLabel) {
        CGFloat height = (kHeight - kNavgationBar - kBottomPadding)/2;
        _contentLabel = [[LSTYAttributedLabel alloc] initWithFrame:CGRectMake(10, height-180,kWidth-20,10)];
        _contentLabel.numberOfLines = 0;
        _contentLabel.linesSpacing = 5;
        _contentLabel.font = FONT(15);
        _contentLabel.backgroundColor = [UIColor whiteColor];
        _contentLabel.delegate = self;
        _contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
        
    }
    return _contentLabel;
}

- (KZWaveRecordingView *)recordView {
    if (!_recordView) {
        _recordView = [[KZWaveRecordingView alloc] init];
        _recordView.frame = CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
    }
    return _recordView;
}

- (KZAudioPlayOrRecordView *)volumeView {
    if (!_volumeView) {
        _volumeView = [[KZAudioPlayOrRecordView alloc] init];
        _volumeView.frame = CGRectMake((kWidth-138)/2, tipHeight+bottomY, 138, 20);
    }
    return _volumeView;
}

- (UIView*)tipsView {
    if (!_tipsView) {
        _tipsView = [[UIView alloc] init];
    }
    
    return _tipsView;
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(40,tipHeight+bottomY,kWidth-80, 12)];
        _tipLabel.textColor = [UIColor colorWithHex:0x4a4a4a];
        _tipLabel.font = [UIFont systemFontOfSize:11];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.numberOfLines = 0;
    }
    return _tipLabel;
}

- (UIImageView *)evaluatingView {
    if (!_evaluatingView) {
        _evaluatingView = [[UIImageView alloc] init];
        _evaluatingView.frame = CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
    }
    return _evaluatingView;
}

- (UILabel *)resultLabel {
    if (!_resultLabel) {
        _resultLabel = [[UILabel alloc] init];
        _resultLabel.frame =  CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
        _resultLabel.layer.cornerRadius = 35;
        _resultLabel.layer.masksToBounds = YES;
        _resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
        _resultLabel.textAlignment = NSTextAlignmentCenter;
        _resultLabel.textColor = [UIColor whiteColor];
    }
    return _resultLabel;
}

- (UIButton *)reReadBtn {
    if (!_reReadBtn) {
        _reReadBtn = [[UIButton alloc] init];
        _reReadBtn.frame = CGRectMake((kWidth/2-144-10),tipHeight+bottomY,144, 44);
        _reReadBtn.titleLabel.font = FONT(14);
        _reReadBtn.layer.cornerRadius = 6;
        _reReadBtn.layer.masksToBounds = YES;
        _reReadBtn.layer.borderWidth = 1.0f;
        _reReadBtn.layer.borderColor = [UIColor colorWithHex:0x19cdc7].CGColor;
        [_reReadBtn setTitleColor:[UIColor colorWithHex:0x19cdc7] forState:UIControlStateNormal];
        [_reReadBtn setTitle:@"重新跟读" forState:UIControlStateNormal];
        [_reReadBtn addTarget:self action:@selector(reAnswerAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _reReadBtn;
}

- (KZShadowButton *)nextBtn {
    if (!_nextBtn) {
        WeakObj(self);
        _nextBtn = [[KZShadowButton alloc] init:^(UIButton *button) {
            button.backgroundColor = RGBA(11, 178, 242, 1);
            [button setTitle:@"下一题" forState:UIControlStateNormal];
            button.titleLabel.font = FONT(14);
            if (selfWeak.currentIndex+1 == selfWeak.allCount) {
                [button setTitle:@"查看结果" forState:UIControlStateNormal];
            }
        }];
        _nextBtn.frame = CGRectMake(kWidth/2+10, tipHeight+bottomY,144, 44);
        [_nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if(_isNoMore) {
            [_nextBtn.button setTitle:@"没有更多" forState:UIControlStateNormal] ;
            _nextBtn.button.backgroundColor = [UIColor colorWithHex:0xe1e2e2];
            _nextBtn.enabled = NO;
        }
    }
    return _nextBtn;
}

- (UIButton *)myRecordBtn {
    if (!_myRecordBtn) {
        CGFloat Y = self.contentLabel.y + self.contentLabel.height + 10;
        _myRecordBtn = [[UIButton alloc] init];
        _myRecordBtn.frame = CGRectMake(-80,Y, 80, 20);
        [_myRecordBtn setImage:[UIImage imageNamed:@"LS-我的录音图标"] forState:UIControlStateNormal];
        [_myRecordBtn setTitle:@"我的录音" forState:UIControlStateNormal];
        _myRecordBtn.imageEdgeInsets = UIEdgeInsetsMake(0,50, 0, -50);
        _myRecordBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-25,0,25);
        _myRecordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [_myRecordBtn setTitleColor:[UIColor colorWithHex:0x464646] forState:UIControlStateNormal];
        [_myRecordBtn addTarget:self action:@selector(myRecordPlayAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _myRecordBtn;
}

- (UIButton *)trueRecordBtn {
    if (!_trueRecordBtn) {
        _trueRecordBtn = [[UIButton alloc] init];
        CGFloat Y = self.contentLabel.y + self.contentLabel.height + 10;
      
        _trueRecordBtn.frame = CGRectMake(kWidth,Y, 80, 20);
        [_trueRecordBtn setImage:[UIImage imageNamed:@"LS-参考示范图标"] forState:UIControlStateNormal];
        [_trueRecordBtn setTitle:@"参考示范" forState:UIControlStateNormal];
        [_trueRecordBtn setTitleColor:[UIColor colorWithHex:0x464646] forState:UIControlStateNormal];
        //        button.imageEdgeInsets = UIEdgeInsetsMake(0, titleW, 0, -titleW)//设置图片位置
        //        button.titleEdgeInsets = UIEdgeInsetsMake(0, -(imgW + titleImgMargin), 0, (imgW + titleImgMargin))
        _trueRecordBtn.imageEdgeInsets = UIEdgeInsetsMake(0,50,0,-50);
        _trueRecordBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-25,0,25);
        _trueRecordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [_trueRecordBtn addTarget:self action:@selector(trueRecordPlayAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _trueRecordBtn;
}


#pragma mark - playerDelegate
- (void)audioUpdateWith:(float)time Totaltime:(float)totalTime {
    self.isPlaying = YES;
}

- (void)audioPlayEnd {
    NSLog(@"播放完");
    self.isPlaying = NO;
    if (_isPlayAction==NO) {
        
        [self.volumeView freeSource];

        //初始化定时器并暂停
        self.second = 0;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(indicatorViewEnd) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        [UIView animateWithDuration:0.3 animations:^{
            
            self.volumeView.alpha = 0.5;
            self.playBtn.alpha = 0.5;
            self.tipLabel.y = bottomY+tipHeight;
            
        } completion:^(BOOL finished) {
            
            self.volumeView.alpha = 0.0;
            [self.volumeView removeFromSuperview];
            self.volumeView = nil;
            self.playBtn.alpha = 0;
            [self.playBtn removeFromSuperview];
            self.playBtn = nil;
            
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;
            
            [self.tipsView addSubview:self.tipLabel];
            self.tipLabel.text = @"请在指示灯全部消失后,开始跟读...";
            
            [self addSubview:self.indicatorView];
            [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.contentLabel.mas_top);
                make.left.equalTo(self).offset(-100);
                make.size.mas_equalTo(CGSizeMake(80, 35));
            }];
            [UIView animateWithDuration:0.3 animations:^{
                
                self.tipLabel.y = (tipHeight-12)/2;
                
                [self.indicatorView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self);
                }];
                [self layoutIfNeeded];
                
            } completion:^(BOOL finished) {
                
            }];
        }];
    }
    _isPlayAction=NO;
}

#pragma mark - 定时器相关方法
//指示灯倒计时
- (void)indicatorViewEnd {
    UIImageView *imageView = [_indicatorView viewWithTag:1000+(int)self.second];
    self.second = self.second + 1.0;
    imageView.alpha = 0;
    if (self.second==4.0) {
        
        NSLog(@"indicatorViewEnd");
        [self.timer invalidate];
        self.timer = nil;
        
        [self.indicatorView removeFromSuperview];
        self.indicatorView = nil;
        [self.tipsView addSubview:self.recordView];
        [self.tipsView addSubview:self.volumeView];
        [self.tipsView addSubview:self.tipLabel];
        self.tipLabel.text = @"请跟随文字高亮进度进行跟读...";
        
        //初始化录音并暂停
        self.second = 0;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(recordTestEnd) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        
        //配置评测参数
        KYTestConfig *config = [[KYTestConfig alloc] init];
        config.coreType = KYTestType_Sentence;
        config.refText = self.attr.string;
        config.phonemeOption = KYPhonemeOption_KK;
        config.audioType = @"wav";
        config.sampleRate = 16000;
        config.sampleBytes = 2;
        config.soundIntensityEnable = NO;
        
        __weak typeof(self) weakSelf = self;
        [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
            weakSelf.testResult = testResult;
        }];

        self.recordView.y = 10;
        self.volumeView.y = 85;

        [UIView animateWithDuration:0.3 animations:^{
            
            self.tipLabel.y = tipHeight+bottomY;
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.3 animations:^{
                
//                self.recordView.y = 10;
//                self.volumeView.y = 85;
                self.tipLabel.y = 115;
                
            } completion:^(BOOL finished) {
                
            }];
        }];
    }
}

//录音评测计时
- (void)recordTestEnd {
    CGFloat totalTime = [self.contentLabel.attributedText.string componentsSeparatedByString:@" "].count /  _readRate;
    self.second = self.second + 0.05;
    CGFloat len = (self.second/totalTime * self.contentLabel.attributedText.string.length);
    if (len >= self.contentLabel.attributedText.string.length) {
        len = self.contentLabel.attributedText.string.length;
    }
    NSRange range = NSMakeRange(0, len);
    [self.attr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:range];
    self.contentLabel.attributedText = self.attr;
    
    if (self.second>=totalTime+2) {
        NSLog(@"recordTestEnd");
        [self.timer invalidate];
        self.timer = nil;
        
        //初始化并暂停录音
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(loadingEvaluatingView:) userInfo:nil repeats:NO];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        //结束评测，返回结果
        [[KYTestEngine sharedInstance] stopEngine];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.volumeView.y = tipHeight+bottomY;
            self.recordView.y = tipHeight+bottomY;
            self.tipLabel.y = tipHeight+bottomY;
            
        } completion:^(BOOL finished) {
            
            [self.recordView removeFromSuperview];
            self.recordView = nil;
            [self.volumeView removeFromSuperview];
            [self.volumeView freeSource];
            self.volumeView = nil;
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;
            
            [self.tipsView addSubview:self.evaluatingView];
            [self.evaluatingView gif:@"__4"];
            [self.tipsView addSubview:self.tipLabel];
            self.tipLabel.text = @"系统正在给您评判,请稍等...";
            [UIView animateWithDuration:0.3 animations:^{
                
                self.evaluatingView.y = 10;
                self.tipLabel.y = 85;
                
            } completion:^(BOOL finished) {
                
                
            }];
            
            
        }];
    }
}

//加载评测结果动画
- (void)loadingEvaluatingView:(NSTimer*)time {
    
    //NSString *testResult = self.testResult;//(NSString*)time.userInfo;
    [self.timer invalidate];
    self.timer = nil;
    self.tipLabel.y = bottomY+tipHeight;
    [self.tipLabel removeFromSuperview];
    self.tipLabel = nil;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.evaluatingView.y = bottomY+tipHeight;
        
    } completion:^(BOOL finished) {

        [self.evaluatingView removeFromSuperview];
        self.evaluatingView = nil;

    }];
    
    //结束评测，返回结果
    [self showResult:self.testResult];    
}

#pragma mark - 解析评测结果
- (void)showResult:(NSString *)result {
    
    self.pasueState = 1;
    self.answerState = 1;
    
    if([result rangeOfString:@"errId"].length > 0) {  //错误回调
        
        NSLog(@"result：%@",result);
        [MBProgressHUD showOnlyText:@"口语评测错误" position:KZHUDPositionModeCenter duration:3];
        
    } else if ([result rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
        NSLog(@"音量：%f",soundIntensity/100.0f);
        
    } else {
        NSError *error;
        if (result == nil) {
            result = @"{\"result\" : {\"overall\" : 0}}";
        }
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"showResult");
            NSString *str = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
            NSLog(@"评测结果:%@",str);
            //保存回调
            if(self.isReAnswer==NO) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(FinishAnswerSenDict:RefText:IsSave:)]) {
                    [self.delegate FinishAnswerSenDict:resultDic RefText:self.attr.string IsSave:NO];
                }
            }
            
            [self.tipsView addSubview:self.resultLabel];
            
            if (self.isReAnswer==NO) { //第一次作答错误
                self.isReAnswer = YES;
                [self.tipsView addSubview:self.tipLabel];
                
                //初始化定时器并暂停
                self.second = 3.0f;
                if (str.integerValue>=LS_System.readScore) {//合格自动进入下一题
                    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(enterNextQues) userInfo:nil repeats:YES];
                    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                }
                else {
                    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(reAnswerControl) userInfo:nil repeats:YES];
                    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                }
                
                [UIView animateWithDuration:0.5 animations:^{
                    if (str.integerValue>=LS_System.readScore) {
                        self.resultLabel.text = @"合格";
                        self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                        self.resultLabel.y = 10;
                        self.tipLabel.y = 85;
                        
                        self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入下一题",(int)self.second];
                        if (self.currentIndex+1 == self.allCount) {
                            self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入查看结果",(int)self.second];
                            //代理回调
                            if(self.moudleID==2) {
                                
                                [self.timer invalidate];
                                self.timer = nil;
                                self.tipLabel.text = @"系统评判结果";
                                
                                if(self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                                    [self.delegate retrunShowComplteView];
                                }
                            }
                        }
                        
                    } else {
                        self.resultLabel.text = @"不合格";
                        self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                        self.resultLabel.y = 10;
                        self.tipLabel.y = 85;
                        
                        self.tipLabel.text = [NSString stringWithFormat:@"重新跟读，请准备...%ds",(int)self.second];
                        
                    }
                } completion:^(BOOL finished) {
                   
                    
                }];
                
            } else {//非第一次错误
                [self.tipsView addSubview:self.tipLabel];
                self.tipLabel.text = @"系统评判结果";
                
                [self.tipsView addSubview:self.reReadBtn];
                [self.tipsView addSubview:self.nextBtn];
                
                [self addSubview:self.trueRecordBtn];
                [self addSubview:self.myRecordBtn];
                
                [UIView animateWithDuration:0.5 animations:^{
                    
                    self.myRecordBtn.x = 10;
                    self.trueRecordBtn.x = kWidth-10-80;
                    
                    if (str.integerValue>=LS_System.readScore) {
                        
                        self.resultLabel.text = @"合格";
                        self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                        self.resultLabel.y = 10;
                        self.tipLabel.y = 85;
                        
//                        self.nextBtn.y = tipHeight-44-20;
//                        self.nextBtn.centerX = self.tipsView.centerX;
                        self.reReadBtn.y = tipHeight-44-20;
                        self.nextBtn.y = tipHeight-44-20;
                        
                    } else {
                        
                        self.resultLabel.text = @"不合格";
                        self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                        self.resultLabel.y = 10;
                        self.tipLabel.y = 85;
                        
                        self.reReadBtn.y = tipHeight-44-20;
                        self.nextBtn.y = tipHeight-44-20;
                    }
                    
                } completion:^(BOOL finished) {
                    
                    //错题最后一题回调
                    if (!self.isUseReAnswerBtn && (self.currentIndex+1 == self.allCount)) {
                        if(self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                            [self.delegate retrunShowComplteView];
                        }
                    }
                    
                    //调用知识点分析
                    if (self.isReAnswer) {
                        
                        NSString *testString = @"";
                        NSArray *words = jsonresult[@"words"];
                        for (NSInteger i = 0; i<words.count; i++) {
                            NSDictionary *word = words[i];
                            NSNumber *num = word[@"scores"][@"overall"];
                            if (num.integerValue<LS_System.readScore) {
                                testString = [NSString stringWithFormat:@"%@ %@",testString,word[@"word"]];
                            }
                        }
                        NSLog(@"testString=%@",testString);
                        
                        self.zsdLabel = [[LSTYAttributedLabel alloc] initWithFrame:self.contentLabel.frame];
                        self.zsdLabel.backgroundColor = [UIColor whiteColor];
                        self.zsdLabel.attributedText = self.contentLabel.attributedText;
                        self.zsdLabel.textColor = [UIColor blackColor];
                        self.zsdLabel.delegate = self;
                        self.zsdLabel.isTextBackgroundColor = YES;
                        self.zsdLabel.textBackgroundColor = [UIColor orangeColor];
                        [self addSubview:self.zsdLabel];
                        [self setupLabel:self.zsdLabel HightlightlyString:self.zsdLabel.attributedText.string Words:_mutlNameArr Codes:_mutlCodeArr];
                        LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
                        manager.requestParam = @{@"Text":testString,
                                                 @"stageNo":KGetUserDefaults(@"TestLayer")
                                                 };
                        WeakObj(self);
                        [MBProgressHUD showDefaultToView:self.zsdLabel];
                        [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {

                            NSMutableArray *mutlCodeArr = [NSMutableArray array];
                            NSMutableArray *mutlNameArr = [NSMutableArray array];
                            for (LSModelZSD *zsd in zsdArr) {
                                [mutlCodeArr addObject:zsd.ZSDCode];
                                [mutlNameArr addObject:zsd.ZSDNameInText];
                            }
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [selfWeak setupLabel:self.zsdLabel HightlightlyString:self.zsdLabel.attributedText.string Words:mutlNameArr Codes:mutlCodeArr];
                                [MBProgressHUD hideHUDForView:self.zsdLabel animated:YES];
                            });

                        } failuer:^(NSString *error) {

                        }];
                    }

                    
                }];
            }
        });
    }
}

- (void)getZSDHightly:(NSString*)text {
    LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
    manager.requestParam = @{@"Text":text,
                             @"stageNo":KGetUserDefaults(@"TestLayer")
                             };
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {
        
        selfWeak.mutlCodeArr = [NSMutableArray array];
        selfWeak.mutlNameArr = [NSMutableArray array];
        for (LSModelZSD *zsd in zsdArr) {
            [selfWeak.mutlCodeArr addObject:zsd.ZSDCode];
            [selfWeak.mutlNameArr addObject:zsd.ZSDNameInText];
        }
        
    } failuer:^(NSString *error) {
        
    }];
}

- (void)enterNextQues {
    self.second = self.second-1.0;
    self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入下一题",(int)self.second];
    if (self.currentIndex+1 == self.allCount) {
        self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入查看结果",(int)self.second];
    }
    if (self.second<=0.0) {
        [self.timer invalidate];
        self.timer = nil;
        if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
            [self.delegate willEnterNextQues];
        }
    }
}

- (void)reAnswerControl {
    self.second = self.second-1.0;
    self.tipLabel.text = [NSString stringWithFormat:@"重新跟读，请准备...%ds",(int)self.second];
    if (self.second<=0.0) {
        
        self.pasueState = 2;
        
        [self.timer invalidate];
        self.timer = nil;
       
        [self.attr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, self.attr.string.length)];
        self.contentLabel.attributedText = self.attr;
        
        [self startTimeCircle];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.resultLabel.y = bottomY+tipHeight;
            /*self.tipLabel.y = bottomY+tipHeight;*/
            
        } completion:^(BOOL finished) {
            
            [self.resultLabel removeFromSuperview];
            self.resultLabel = nil;
            
            /*
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;*/
            
            /*
            [self addSubview:self.playBtn];
            self.playBtn.y = self.contentLabel.y + self.contentLabel.height+10;
            
            [self addSubview:self.volumeView];
            [self.volumeView pauseSource];
            self.volumeView.y = self.playBtn.y+50;
            
            [self.tipsView addSubview:self.tipLabel];
            self.tipLabel.text = @"请听标准句子发音...";
            [UIView animateWithDuration:0.3 animations:^{
                self.tipLabel.y = 0;
            } completion:^(BOOL finished) {
                [self.volumeView beginSource];
                NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
                [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
            }];*/
            
        }];
        
    }

}

#pragma mark - buttonAtion
- (void)reAnswerAction:(id)sender {
    
    self.isUseReAnswerBtn = YES;
    
    self.pasueState = 2;
    
    [self.attr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, self.attr.string.length)];
    self.contentLabel.attributedText = self.attr;
    
    [self.zsdLabel removeFromSuperview];
    self.zsdLabel = nil;
    
    [self startTimeCircle];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.resultLabel.y = bottomY+tipHeight;
        /*self.tipLabel.y = bottomY+tipHeight;*/
        self.reReadBtn.y = bottomY+tipHeight;
        self.nextBtn.y = bottomY+tipHeight;
        self.myRecordBtn.x = -80;
        self.trueRecordBtn.x = kWidth;
        
    } completion:^(BOOL finished) {
        
        [self.resultLabel removeFromSuperview];
        self.resultLabel = nil;
        
       /* [self.tipLabel removeFromSuperview];
        self.tipLabel = nil;*/
        
        [self.reReadBtn removeFromSuperview];
        self.reReadBtn = nil;
        [self.nextBtn removeFromSuperview];
        self.nextBtn = nil;
        [self.myRecordBtn removeFromSuperview];
        self.myRecordBtn = nil;
        [self.trueRecordBtn removeFromSuperview];
        self.trueRecordBtn = nil;
        
        /*
        [self addSubview:self.playBtn];
        self.playBtn.y = self.contentLabel.y + self.contentLabel.height+10;
        
        [self addSubview:self.volumeView];
        [self.volumeView beginSource];
        self.volumeView.y = self.playBtn.y+50;
        
        [self.tipsView addSubview:self.tipLabel];
        self.tipLabel.text = @"请听标准句子发音...";
        [UIView animateWithDuration:0.3 animations:^{
            self.tipLabel.y = 0;
        } completion:^(BOOL finished) {
            //[self.volumeView beginSource];
             _isPlayAction = NO;
            NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
            [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
        }];*/
        
    }];
}

- (void)nextBtnAction:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
        [self.delegate willEnterNextQues];
    }
}

- (void)myRecordPlayAction:(id)sender {
    _isPlayAction = YES;
    NSString *wavPath = [KYTestEngine sharedInstance].currentWavPath;
    NSLog(@"wavPath=%@",wavPath);
    //  [[KYTestEngine sharedInstance] playback];
    NSURL *url = [NSURL fileURLWithPath:wavPath];
    [self.player playerUrl:url seekTotime:0 rateValue:1.0];
}

- (void)trueRecordPlayAction:(id)sender {
    _isPlayAction = YES;
    NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
    
    if (_playRate == 0) {
        _playRate = 1;
    }
    [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
}

#pragma mark - 取消定时器/暂停
- (void)TimeReleaseAction {
    NSLog(@"释放时间");
    [self.timer invalidate];
    self.timer = nil;
    [self.player closePlayer];
    [[KYTestEngine sharedInstance] cancelEngine];
    [self.volumeView freeSource];
}

- (void)TimePauseAction {
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.volumeView pauseSource];
    [self.recordView pauseSource];
    if (self.isPlaying) {
        [self.player playerPaused];
    }
    [[KYTestEngine sharedInstance] pauseEngine];
}

- (void)TimeResumeAction {
    [self.timer setFireDate:[NSDate distantPast]];
    [self.volumeView beginSource];
    [self.recordView beginSource];
    if (self.isPlaying) {
        [self.player playerPlay];
    }
    [[KYTestEngine sharedInstance] resumeEngine];
}


- (void)stopClickNextBtn {
    [self.nextBtn.button setTitle:@"没有更多" forState:UIControlStateNormal] ;
    self.nextBtn.button.backgroundColor = [UIColor colorWithHex:0xe1e2e2];
    self.nextBtn.enabled = NO;
    _isNoMore = YES;
}

#pragma mark - LSTYAttributedLabelDelegate
- (void)attributedLabel:(LSTYAttributedLabel *)attributedLabel textStorageClicked:(id<LSTYTextStorageProtocol>)TextRun atPoint:(CGPoint)point atRect:(CGRect)rect{
    NSString *linkStr = ((TYLinkTextStorage*)TextRun).linkData;
    
    if (![linkStr isEqualToString:@""]) {
        
        //知识点课件显示及保存
        _dictView = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
        _dictView.delegate = self;
        _dictView.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
        _dictView.dictParam = @{
                                @"knowledge":[linkStr componentsSeparatedByString:@"|"].firstObject,
                                @"levelCode":KGetUserDefaults(@"TestLayer"),
                                @"stageNo":KGetUserDefaults(@"TestLayer"),
                                @"schoolId":DR_UserInfo.SchoolID,
                                @"stuId":DR_UserInfo.UserID,
                                };
        
        [_dictView popAnimated:YES];
        
        LSSaveZSDManager *manager = [[LSSaveZSDManager alloc] init];
        NSDictionary *dict = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                               @"SchoolID":KGetUserDefaults(@"SchoolID"),
                               @"StuID":DR_UserInfo.UserID,
                               @"VocabularyID":[linkStr componentsSeparatedByString:@"|"].firstObject,
                               @"Vocabulary":[linkStr componentsSeparatedByString:@"|"].lastObject,
                               @"IsPassed":@0,
                               @"ReviewPassedCount":@0,
                               @"NeedReviewCount":@3,
                               @"CreateTime":[NSDate date],
                               @"UpdateTime":[NSDate date]
                               };
        NSLog(@"%@",dict);
        manager.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                                 @"schoolId":DR_UserInfo.SchoolID,
                                 @"stuId":DR_UserInfo.UserID,
                                 @"ModelUnfamiliarVocabularyList":@[dict]
                                 };
        
        [manager requestSaveWithCompltionSuccess:^(NSString *string) {
            NSLog(@"保存知识点");
        } failuer:^(NSString *error) {
            
        }];
        
    }

    
}

#pragma mark - //**加载高亮**//
- (void)setupLabel:(LSTYAttributedLabel*)textLabel HightlightlyString:(NSString*)text Words:(NSArray*)words Codes:(NSArray*)codes{
    NSString *string = text;
    
    NSMutableArray *removeHadArr = [NSMutableArray array];
    [string enumerateSubstringsInRange:NSMakeRange(0, string.length-1) options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        
        if([words containsObject:substring] && ![removeHadArr containsObject:substring]) {
            
            [removeHadArr addObject:substring];
            
            NSInteger index = [words indexOfObject:substring];
            //NSString *linkData = codes[index];
            NSString *linkData = [NSString stringWithFormat:@"%@|%@",codes[index],substring];
            [textLabel addLinkWithLinkData:linkData linkColor:[UIColor whiteColor] underLineStyle:kCTUnderlineStyleNone range:substringRange];
            //textLabel.linesSpacing = 10;
        }
    }];
}

#pragma mark - DicMainViewDelegate
- (void)colseDicMainView:(UIView *)dictView {
    [dictView removeFromSuperview];
    dictView = nil;
}

//分句时暂停
- (void)stratReAnswer {
    
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;
        
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    if (self.pasueState==0) {
        [self TimeReleaseAction];
        [self clearSubView];
        [self createUI];
    } else if (self.pasueState==2) {
        self.isReAnswer = YES;
        [self TimeReleaseAction];
        [self clearSubView];
        [self createUI];
    }
}

//暂停后清理子视图
- (void)clearSubView {
    [self.titleBarView removeFromSuperview];
    self.titleBarView = nil;
    
    [self.contentLabel removeFromSuperview];
    self.contentLabel = nil;
    
    [self.playBtn removeFromSuperview];
    self.playBtn = nil;
    
    [self.tipsView removeFromSuperview];
    self.tipsView = nil;
    
    [self.tipLabel removeFromSuperview];
    self.tipLabel = nil;
    
    [self.indicatorView removeFromSuperview];
    self.indicatorView = nil;
    
    [self.recordView removeFromSuperview];
    self.recordView = nil;
    
    [self.volumeView removeFromSuperview];
    [self.volumeView freeSource];
    self.volumeView = nil;
    
    [self.evaluatingView removeFromSuperview];
    self.evaluatingView = nil;
}


@end
